<template>
  <view class="record-detail-page">
    <view class="page-header">
      <text class="page-title">病例详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button v-if="canEdit" class="btn btn-primary" @click="handleEdit">编辑</button>
        <button v-if="canDelete" class="btn btn-danger" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <!-- 基本信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
          <view class="status-group">
            <text class="status-badge" :class="'status-' + record.status">{{ getStatusText(record.status) }}</text>
            <text class="permission-badge" :class="(record.can_edit !== undefined ? record.can_edit : !record.is_read_only) ? 'editable' : 'readonly'">{{ (record.can_edit !== undefined ? record.can_edit : !record.is_read_only) ? '可编辑' : '只读' }}</text>
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">患者姓名</text>
            <text class="value">{{ record.patient_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">主治医师</text>
            <text class="value">{{ record.doctor_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">就诊日期</text>
            <text class="value">{{ formatTime(record.visit_date) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">症状描述</text>
            <text class="value">{{ record.symptoms || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 诊断信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">诊断信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">诊断结果</text>
            <text class="value">{{ record.diagnosis || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">治疗方案</text>
            <text class="value">{{ record.treatment_plan || '-' }}</text>
          </view>
          
          <view v-if="record.notes" class="detail-row">
            <text class="label">备注信息</text>
            <text class="value">{{ record.notes }}</text>
          </view>
        </view>
      </view>

      <!-- 处方信息 -->
      <view v-if="record.prescription && record.prescription.length > 0" class="detail-card">
        <view class="card-header">
          <text class="card-title">处方信息</text>
        </view>
        <view class="card-body">
          <view v-for="(item, index) in record.prescription" :key="index" class="prescription-item">
            <view class="prescription-header">
              <text class="prescription-title">{{ item.medicine_name || '-' }}</text>
            </view>
            <view class="prescription-details">
              <text class="prescription-text">剂量：{{ item.dosage || '-' }}</text>
              <text class="prescription-text">用药频率：{{ item.frequency || '-' }}</text>
              <text class="prescription-text">疗程：{{ item.duration || '-' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 检查结果 -->
      <view v-if="record.examination_results && record.examination_results.length > 0" class="detail-card">
        <view class="card-header">
          <text class="card-title">检查结果</text>
        </view>
        <view class="card-body">
          <view v-for="(item, index) in record.examination_results" :key="index" class="examination-item">
            <view class="examination-name">{{ item.exam_type || '-' }}</view>
            <view class="examination-result">{{ item.exam_result || '-' }}</view>
            <view v-if="item.file_url" class="examination-file">
              <text class="file-link">查看报告</text>
            </view>
            <!-- 检查结果图片 -->
            <view v-if="item.images && item.images.length > 0" class="examination-images">
              <view class="images-grid">
                <view v-for="(img, imgIndex) in item.images" :key="imgIndex" class="image-item">
                  <image :src="getImageUrl(img)" mode="aspectFill" class="image" @click="previewExamImage(item.images, img)" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 协助护士 -->
      <view v-if="record.assisting_nurses && record.assisting_nurses.length > 0" class="detail-card">
        <view class="card-header">
          <text class="card-title">协助护士</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">护士人数</text>
            <text class="value">{{ record.assisting_nurses.length }}人</text>
          </view>
          <view v-if="record.nurse_names && record.nurse_names.length > 0" class="detail-row">
            <text class="label">护士名单</text>
            <text class="value">{{ record.nurse_names.join('、') }}</text>
          </view>
        </view>
      </view>

      <!-- 影像资料 -->
      <view v-if="record.images && record.images.length > 0" class="detail-card">
        <view class="card-header">
          <text class="card-title">影像资料</text>
        </view>
        <view class="card-body">
          <view class="images-grid">
            <view v-for="(img, index) in record.images" :key="index" class="image-item">
              <image :src="getImageUrl(img)" mode="aspectFill" class="image" @click="previewImage(img, index)" />
            </view>
          </view>
        </view>
      </view>

      <!-- 转移历史 -->
      <view v-if="record.transfer_history && record.transfer_history.length > 0" class="detail-card">
        <view class="card-header">
          <text class="card-title">转移历史</text>
        </view>
        <view class="card-body">
          <view v-for="(item, index) in record.transfer_history" :key="index" class="transfer-item">
            <view class="transfer-info">
              <text class="transfer-label">转移时间：</text>
              <text class="transfer-value">{{ formatTime(item.transfer_date) }}</text>
            </view>
            <view class="transfer-info">
              <text class="transfer-label">原医师 → 新医师</text>
            </view>
            <view v-if="item.reason" class="transfer-info">
              <text class="transfer-label">转移原因：</text>
              <text class="transfer-value">{{ item.reason }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(record.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(record.update_time) }}</text>
          </view>
          
          <view v-if="record.archive_time" class="detail-row">
            <text class="label">归档时间</text>
            <text class="value">{{ formatTime(record.archive_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { store as uniIdPagesStore } from '@/uni_modules/uni-id-pages/common/store.js'
const loading = ref(true)
const recordId = ref('')
const record = reactive({
  _id: '',
  patient_id: '',
  doctor_id: '',
  visit_date: null,
  symptoms: '',
  diagnosis: '',
  treatment_plan: '',
  prescription: [],
  examination_results: [],
  images: [],
  assisting_nurses: [],
  nurse_names: [],
  status: 0,
  is_read_only: false,
  notes: '',
  transfer_history: [],
  archive_time: null,
  create_time: null,
  update_time: null,
  patient_info: null
})

// 获取当前用户角色
const userInfo = computed(() => uniIdPagesStore.userInfo || {})
const userRoles = computed(() => {
  const roles = userInfo.value?.role || []
  return Array.isArray(roles) ? roles : (roles ? [roles] : [])
})

// 检查是否为超级管理员
const isSuperAdmin = computed(() => {
  return userRoles.value.some(role => ['admin', 'manager'].includes(role))
})

// 检查是否可以编辑病例（使用后端返回的 can_edit 字段）
const canEdit = computed(() => {
  // 如果后端返回了 can_edit 字段，直接使用
  if (record.can_edit !== undefined) {
    return record.can_edit === true
  }
  // 兼容旧数据：如果没有 can_edit 字段，使用 is_read_only 判断
  return !record.is_read_only
})

// 检查是否可以删除病例（仅超级管理员）
const canDelete = computed(() => {
  return isSuperAdmin.value
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  recordId.value = currentPage.options.id || ''
  
  if (!recordId.value) {
    uni.showToast({ title: '缺少病例ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/medical_records/list' })
    }, 1500)
    return
  }
  
  await loadRecordData()
  loading.value = false
})

async function loadRecordData() {
  try {
    const dhMedicalRecords = uniCloud.importObject('dh-medical_records')
    const result = await dhMedicalRecords.getMedicalRecordById(recordId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(record, result.data)
      // 协助护士姓名已由后端返回，无需前端再次查询
    } else {
      throw new Error(result.message || '病例不存在')
    }
  } catch (err) {
    console.error('加载病例数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/medical_records/list' })
    }, 1500)
  }
}

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') {
    return imageData
  }
  if (typeof imageData === 'object' && imageData.url) {
    return imageData.url
  }
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    if (typeof first === 'string') {
      if (first.startsWith('blob:')) return ''
      return first
    }
    if (first.url && !first.url.startsWith('blob:')) {
      return first.url
    }
  }
  return ''
}

function previewImage(currentImage, currentIndex = 0) {
  const imageUrls = record.images.map(img => getImageUrl(img)).filter(url => url && !url.startsWith('blob:'))
  const currentImageUrl = getImageUrl(currentImage)
  if (imageUrls.length === 0) {
    uni.showToast({ title: '没有可预览的图片', icon: 'none' })
    return
  }
  uni.previewImage({
    urls: imageUrls,
    current: currentImageUrl || imageUrls[currentIndex] || imageUrls[0]
  })
}

function previewExamImage(images, currentImage) {
  const imageUrls = images.map(img => getImageUrl(img)).filter(url => url && !url.startsWith('blob:'))
  const currentImageUrl = getImageUrl(currentImage)
  if (imageUrls.length === 0) {
    uni.showToast({ title: '没有可预览的图片', icon: 'none' })
    return
  }
  uni.previewImage({
    urls: imageUrls,
    current: currentImageUrl || imageUrls[0]
  })
}

function getStatusText(status) {
  const statusMap = {
    0: '初诊',
    1: '复诊',
    2: '治疗中',
    3: '已完成',
    4: '已归档'
  }
  return statusMap[status] || '未知'
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/medical_records/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/medical_records/edit?id=${recordId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此病例吗？删除后无法恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          const dhMedicalRecords = uniCloud.importObject('dh-medical_records')
          const result = await dhMedicalRecords.deleteMedicalRecord(recordId.value)
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/medical_records/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
          }
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.record-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-group {
  display: flex;
  gap: 12rpx;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-0 { background: #dbeafe; color: #1e40af; }
  &.status-1 { background: #fef3c7; color: #92400e; }
  &.status-2 { background: #fed7aa; color: #9a3412; }
  &.status-3 { background: #d1fae5; color: #065f46; }
  &.status-4 { background: #e5e7eb; color: #374151; }
}

.permission-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.readonly { background: #fee2e2; color: #7f1d1d; }
  &.editable { background: #d1fae5; color: #065f46; }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-weight: bold;
    color: #007aff;
  }
}

.prescription-item {
  padding: 20rpx;
  background: #f9fafb;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.prescription-header {
  margin-bottom: 12rpx;
}

.prescription-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.prescription-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.prescription-text {
  font-size: 26rpx;
  color: #666;
}

.examination-item {
  padding: 20rpx;
  background: #f9fafb;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.examination-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.examination-result {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.examination-file {
  margin-top: 8rpx;
}

.file-link {
  font-size: 26rpx;
  color: #007aff;
  text-decoration: underline;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.image-item {
  width: 100%;
  padding-bottom: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.transfer-item {
  padding: 20rpx;
  background: #f9fafb;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.transfer-info {
  display: flex;
  margin-bottom: 12rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.transfer-label {
  font-size: 26rpx;
  color: #666;
  min-width: 160rpx;
}

.transfer-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}
</style>

